'use strict';
/**
 * 此处建议只改下订单状态，保证能及时返回给第三方支付服务器成功状态
 * 限制4秒内必须执行完全部的异步回调逻辑，建议将消息发送、返佣、业绩结算等业务逻辑异步处理（如用定时任务去处理这些异步逻辑）
 * 特别注意：因为金额是前端传的，需要再判断下金额和你业务系统订单中的金额是否一致，如果不一致，直接返回 return false;
 * 特别注意：因为金额是前端传的，需要再判断下金额和你业务系统订单中的金额是否一致，如果不一致，直接返回 return false;
 * 特别注意：因为金额是前端传的，需要再判断下金额和你业务系统订单中的金额是否一致，如果不一致，直接返回 return false;
 */
const config = require('../config/index.js')
module.exports = async (obj) => {
	console.log('tool支付回调')
	let user_order_success = true;
	let { data = {} } = obj;
	let {
		order_no,
		out_trade_no,
		paid_time,
		custom = {}
	} = data; // uni-pay-orders 表内的数据均可获取到
  console.log(`回调数据：${JSON.stringify(data)}`)
	const dbName = 'ai-orders'
	// 此处写你自己的支付成功逻辑开始-----------------------------------------------------------
	// 获取你的业务订单信息
  const db = uniCloud.database();
  let orderRes = await db.collection(dbName).where({ _id: order_no }).get();
  let orderInfo = orderRes.data[0];
  let { total_fee, order_type, user_id, extendData } = orderInfo
	// 比对订单信息与支付回调金额是否一致
	if (orderInfo.total_fee === total_fee) {
    // 更新订单信息
		let res = await db.collection(dbName).where({ _id: order_no }).update({
      status: 2
    });

		if (res) {
			user_order_success = true;
		} else {
			user_order_success = false
		}
    
    let timesMap = {
      month:  31 * 24 * 60 * 60 * 1000,
      threeMonth: 3 * 31 * 24 * 60 * 60 * 1000,
      halfYear: 6 * 31 * 24 * 60 * 60 * 1000,
      year: 12 * 31 * 24 * 60 * 60 * 1000
    }
    let priceKey = orderInfo.extendData.priceKey
    
    // 更新工具使用时间
		 const uti = await db.collection('ai-user-tool').where({
			user_id: user_id,
			tool_id: orderInfo.extendData.tool_id
		}).get()
		
		
		let userToolInfo = uti.data[0];
    
    // 用户信息
    let userRes = await db.collection('uni-id-users').where({ _id: user_id }).get();
    let userInfo = userRes.data[0];
    
    // 更新用户的vip
    let expiration_time = new Date().getTime()
    if (userToolInfo && userToolInfo.expiration_time > expiration_time) {
      expiration_time = userToolInfo.expiration_time
    }
    expiration_time = expiration_time + timesMap[priceKey]
   
    if (userToolInfo) {
			await db.collection('ai-user-tool').where({_id: userToolInfo._id}).update({ expiration_time });
    } else {
			await db.collection('ai-user-tool')
			.add({ // 需要新增的数据 json格式
          tool_id: orderInfo.extendData.tool_id,
          user_id: user_id,
          expiration_time,
          buyTime: new Date().getTime()
        })
    }
    
    // 邀请分成		
		let { inviter_uid = '' } = userInfo
		let inviterUserRes = await db.collection('uni-id-users').where({ _id: inviter_uid }).get();
		let inviterUserInfo = inviterUserRes.data[0];
    if (inviterUserInfo) {
			console.log(`inviter_uid: ${inviter_uid}----`)
			let increMoney = parseInt(config.saleRatio * total_fee)
			console.log(`increMoney: ${increMoney}----`)
			await db.collection("uni-id-users").doc(inviterUserInfo._id).update({
			  balance: ([null,undefined].includes(inviterUserInfo.balance) ? 0 : inviterUserInfo.balance) + increMoney,
			  total_revenue: ([null,undefined].includes(inviterUserInfo.total_revenue) ? 0 : inviterUserInfo.total_revenue) + increMoney
			});
			await db.collection("ai-earning-detail").add({
			  user_id: inviterUserInfo._id,
			  amount: increMoney,
			  change_class: 1,
			  change_scene: 1,
			  created_at: new Date().getTime()
			})
		}
    
    // 三级分佣，查找上级邀请者
    let parent_inviter_uid = inviterUserInfo ? inviterUserInfo.inviter_uid : ''
    if (parent_inviter_uid) {
      let parentInviterUserRes = await db.collection('uni-id-users').where({ _id: parent_inviter_uid }).get();
      let parentInviterUserInfo = parentInviterUserRes.data[0];
      if (parentInviterUserInfo) {
        console.log(`parent_inviter_uid: ${parent_inviter_uid}----`)
        let parentIncreMoney = parseInt(config.secondaryRatio * total_fee)
        console.log(`parent increMoney: ${parentIncreMoney}----`)
        await db.collection("uni-id-users").doc(parentInviterUserInfo._id).update({
          balance: ([null,undefined].includes(parentInviterUserInfo.balance) ? 0 : parentInviterUserInfo.balance) + parentIncreMoney,
          total_revenue: ([null,undefined].includes(parentInviterUserInfo.total_revenue) ? 0 : parentInviterUserInfo.total_revenue) + parentIncreMoney
        });
        await db.collection("ai-earning-detail").add({
          user_id: parentInviterUserInfo._id,
          amount: parentIncreMoney,
          change_class: 1,
          change_scene: 2,
          created_at: new Date().getTime()
        })
      }
    }
	}
	
	// 此处写你自己的支付成功逻辑结束-----------------------------------------------------------
	return user_order_success;
};
